package branch;

import java.util.Random;

public class RandomTransactionThread implements Runnable {

	private Branch branch;
	private final int MIN_BRANCH_ID = 1;
	private final int MIN_AMOUNT = 10;
	private final int MIN_WAIT_TIME = 5000; // 5000
	private long startTime = 0, endTime = 0, timeElapsed = 0;
	private Random random;
	
	public RandomTransactionThread(Branch branch) {
		this.branch = branch;
	}
	
	@Override
	public void run() {		
		random = new Random();
		
		//Get Random ID
		int waitTime = 0;
		int distantBranchId = 0;
		int randomAmount = 0;
		int randomWaitTime = 0;
		int branchCount = 0;
		
		randomWaitTime = random.nextInt(5000);
		waitTime = MIN_WAIT_TIME + randomWaitTime;
		
		startTime = System.currentTimeMillis();
		
		while(true) {
			branchCount = branch.getConnectedBranches().size();
			if(branchCount >= 1) {
				try {
					Thread.sleep(waitTime);
					
					System.out.println(String.format("Random Transaction To: %d Amount: %d",distantBranchId,randomAmount));
					
					do {
						
						distantBranchId = branch.getConnectedBranches().get(random.nextInt(branchCount)).getId();
						
					} while(distantBranchId == branch.getLocalBranchDAO().getId());
					
					//Get Random amount
					randomAmount = random.nextInt(branch.getCurrentAmount());
					
					//Send Transfer Transaction
					branch.sendMoneyTransfer(distantBranchId, randomAmount);
					branch.getBranchGUI().addSendTransaction(randomAmount, distantBranchId);
					
					//Get new waitTime
					randomWaitTime = random.nextInt(5000);
					waitTime = MIN_WAIT_TIME + randomWaitTime;
					
				} 
				catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
					
		}
		
	}
	
	
	
}
